package me.zhengjie.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import me.zhengjie.domain.AliOSSConfig;
import me.zhengjie.domain.dto.UploadFileReqDTO;
import me.zhengjie.exception.BadRequestException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.util.UUID;

/**
 * 阿里云 OSS 工具类
 */
@Component
public class OSSUtils {


    @Autowired
    private AliOSSConfig config;

    /**
     * 实现上传文件到OSS
     */
    public String upload(UploadFileReqDTO uploadFileReqDTO) {
        try {

            // 获取上传的文件的输入流
            InputStream inputStream = uploadFileReqDTO.getFile().getInputStream();
            // 避免文件覆盖
            String originalFilename = uploadFileReqDTO.getFile().getOriginalFilename();
            String fileName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
            //上传文件到 OSS
            OSS ossClient = new OSSClientBuilder().build(config.getEndpoint(), config.getAccessKeyId(), config.getAccessKeySecret());
            ossClient.putObject(config.getBucketName(), fileName, inputStream);
            //文件访问路径
            String url = config.getEndpoint().split("//")[0] + "//" + config.getBucketName() + "." + config.getEndpoint().split("//")[1] + "/" + fileName;
            // 关闭ossClient
            ossClient.shutdown();
            return url;
        } catch (Exception e) {
            throw new BadRequestException("上传文件失败");
        }

    }

}

